package com.ibm.dao;


import com.ibm.entity.User;
import com.ibm.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {

    public  List<User> selectUsers() {
        List<User> userList=new ArrayList<>();

        try {
            String sql = "select user_id userId,user_name userName,user_password pwd,user_score score from users";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            userList=  queryRunner.query(sql,new BeanListHandler<User>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userList;

    }

    public static int insertUsers(User user)
    {
        int i=0;
        try{
            String sql="insert into users(user_id,user_name,user_password,user_score)values(?,?,?,?)";
            Object[] params={user.getUserId(),user.getUserName(),user.getPwd(),user.getScore()};
            QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
            i=queryRunner.update(sql, params);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return i;
    }

    public int deleteUser(int userId)
    {
        int i=0;
        try
        {
            String sql="delete from users where user_id=?";
            QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
            i=queryRunner.update(sql,userId);
         }catch (SQLException e)
        {
            e.printStackTrace();
        }
        return i;
    }

    public static User selectUserById(int userId)
    {
        User user=null;
        try{
            String sql="select user_id userId,user_name userName,user_password pwd,user_score score from users where user_id=?";
            QueryRunner queryRunner=new QueryRunner(DruidUtils.getDataSource());
            user=  queryRunner.query(sql, new BeanHandler<>(User.class),userId);
        }catch (SQLException e)
        {
            e.printStackTrace();
        }

        return  user;
    }

    public static int updateUser(User user)
    {
        int i=0;
        try
        {
            String sql="update users set user_name=?,user_password=?,user_score=? where user_id=?";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            Object[] params={user.getUserName(),user.getPwd(),user.getScore(),user.getUserId()};
            i=queryRunner.update(sql, params);
        }catch (SQLException e)
        {
            e.printStackTrace();
        }
        return i;
    }




}
